package com.atguigu.windows;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.TimestampAssignerSupplier;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Flink12_Timer_EventTime {
    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port",10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration);
        env.setParallelism(2);

        DataStreamSource<String> ds = env.socketTextStream("hadoop162", 9999);
        SingleOutputStreamOperator<String> stream = ds.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] datas = value.split(",");
                return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
            }
        }).assignTimestampsAndWatermarks(WatermarkStrategy
                //定义水印最大容忍的延迟时间
                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                //定义那个字段作为水印比较的时间戳
                .withTimestampAssigner(TimestampAssignerSupplier.of(new SerializableTimestampAssigner<WaterSensor>() {
                    @Override
                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                        return element.getTs();
                    }
                }))
        )
                .keyBy(new KeySelector<WaterSensor, String>() {
                    @Override
                    public String getKey(WaterSensor value) throws Exception {
                        return value.getId();
                    }
                })
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                    private long timer;
                    //定义一个场景：当有水位超过50之后，那么就在5s之后发出预警
                    //当注册的定时器触发之后，会在onTimer中进行一系列的动作
                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {

                        //这里干触发定时器时要做的事情
                        System.out.println("当前触发时间：" + timestamp);
                        out.collect("水位超过50啦！！！！！，发出黄色预警！！！！");
                    }

                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {

                        if (value.getVc() >= 50) {
                            //注册定时器，并在获取到当前时间戳5s之后进行触发
                            timer = value.getTs() + 5000;
                            System.out.println("注册定时器时间:" + timer);
                            ctx.timerService().registerEventTimeTimer(timer);
                        } else if (value.getVc() < 20) {
                            //这里再定义一个条件，如果水位下降到20一下，就删除定时器，不触发定时任务
                            //注意，要取消什么样的定时器，那么就需要拿到相同的定时器才能取消
                            ctx.timerService().deleteEventTimeTimer(timer);
                        }
                    }
                });
        stream.print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
